package com.stox.services.indicator.model;

import org.springframework.stereotype.Component;

import com.stox.services.indicator.model.config.BaseIndicatorConfig;
import com.stox.shared.indicator.model.IndicatorBeanDescriptor;
import com.stox.shared.indicator.model.enumeration.IndicatorPosition;

@Component
public class SimpleMovingAverage extends AbstractIndicator<Double, BaseIndicatorConfig> {

	private final IndicatorBeanDescriptor indicatorInfo = new IndicatorBeanDescriptor(
			createDefaultConfiguration(),
			"SimpleMovingAverage",
			IndicatorPosition.OVERLAY_PRICE,
			Double.class);
	
	@Override
	public Double getValue(BaseIndicatorConfig configuration, Double[] in,
			int index) throws UnsupportedOperationException {
		double sum = 0;
		int span = configuration.getSpan();
		for(int i = index; i < index + span; i++){
			sum += in[index];
		}
		return sum/span;
	}

	@Override
	public Double[] getValues(BaseIndicatorConfig configuration, Double[] values)
			throws UnsupportedOperationException {
		Double[] result = new Double[values.length];
		double sum = 0;
		int span = configuration.getSpan();
		int size = values.length;
		for(int i = size - 1; i >= 0; i--){
			if(null == values[i]) continue;
			sum += values[i];
			if(i > size - 1 - span) continue;
			if(null == values[i + span]) continue;
			sum -= values[i + span];
			result[i] = sum/span;
		}
		return result;
	}

	@Override
	public BaseIndicatorConfig createDefaultConfiguration() {
		return new BaseIndicatorConfig();
	}
	
	@Override
	public IndicatorBeanDescriptor getIndicatorBeanDescriptor() {
		return indicatorInfo;
	}

}
